package com.zhku.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhku.base.exception.TaoTaoException;
import com.zhku.base.model.PageParams;
import com.zhku.base.model.PageResult;
import com.zhku.base.model.RestResponse;
import com.zhku.user.feignclient.GoodsClient;
import com.zhku.user.feignclient.TtGoods;
import com.zhku.user.mapper.TtUserShoppingcartMapper;
import com.zhku.user.model.dto.ReturnShoppingCartDto;
import com.zhku.user.model.dto.ShoppingCartByNumDto;
import com.zhku.user.model.dto.ShoppingCartDto;
import com.zhku.user.model.po.TtUserAddress;
import com.zhku.user.model.po.TtUserShoppingcart;
import com.zhku.user.service.TtUserShoppingcartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.rmi.CORBA.Stub;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TtUserShoppingcartServiceImpl extends ServiceImpl<TtUserShoppingcartMapper, TtUserShoppingcart> implements TtUserShoppingcartService {

    @Autowired
    TtUserShoppingcartMapper ttUserShoppingcartMapper;

    @Autowired
    GoodsClient goodsClient;

    @Override
    @Transactional
    public ReturnShoppingCartDto createShoppingcart(ShoppingCartDto shoppingCartDto) {
        String userId = shoppingCartDto.getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        String goodsId = shoppingCartDto.getGoodsId();
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("传入的商品id为空");
        }
        LambdaQueryWrapper<TtUserShoppingcart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtUserShoppingcart::getUserId,userId).eq(TtUserShoppingcart::getGoodsId,goodsId);
        TtUserShoppingcart ttUserShoppingcart = ttUserShoppingcartMapper.selectOne(queryWrapper);
        if (ttUserShoppingcart == null) {
            //当前购物车没有该商品，添加，数量为1
            TtUserShoppingcart ttUserShoppingcartNew = new TtUserShoppingcart();
            ttUserShoppingcartNew.setUserId(userId);
            ttUserShoppingcartNew.setGoodsId(goodsId);
            ttUserShoppingcartNew.setNumber(1);
            String id = UUID.randomUUID().toString();
            ttUserShoppingcartNew.setId(id);
            int insert = ttUserShoppingcartMapper.insert(ttUserShoppingcartNew);
            if (insert <= 0) {
                throw new TaoTaoException("添加商品到购物车失败");
            }
            //根据商品id查询商品信息返回
            RestResponse<TtGoods> response = goodsClient.getGoods(goodsId);
            TtGoods goods = response.getResult();
            ReturnShoppingCartDto returnShoppingCartDto = new ReturnShoppingCartDto();
            BeanUtils.copyProperties(goods,returnShoppingCartDto);
            returnShoppingCartDto.setNumber(ttUserShoppingcartNew.getNumber());
            return returnShoppingCartDto;
        }else {
            //不为空，当前购物车存在该商品，则在原来基础上加一即可
            ttUserShoppingcart.setNumber(ttUserShoppingcart.getNumber()+1);
            //修改
            int i = ttUserShoppingcartMapper.updateById(ttUserShoppingcart);
            if (i <= 0) {
                throw new TaoTaoException("加1操作失败");
            }
        }

        //根据商品id查询商品信息返回
        RestResponse<TtGoods> response = goodsClient.getGoods(goodsId);
        TtGoods goods = response.getResult();
        ReturnShoppingCartDto returnShoppingCartDto = new ReturnShoppingCartDto();
        BeanUtils.copyProperties(goods,returnShoppingCartDto);
        returnShoppingCartDto.setNumber(ttUserShoppingcart.getNumber());
        return returnShoppingCartDto;
    }

    @Override
    @Transactional
    public ReturnShoppingCartDto deleteShoppingcart(ShoppingCartDto shoppingCartDto) {
        String userId = shoppingCartDto.getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        String goodsId = shoppingCartDto.getGoodsId();
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("传入的商品id为空");
        }
        LambdaQueryWrapper<TtUserShoppingcart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtUserShoppingcart::getUserId,userId).eq(TtUserShoppingcart::getGoodsId,goodsId);
        TtUserShoppingcart ttUserShoppingcart = ttUserShoppingcartMapper.selectOne(queryWrapper);
        Integer number = ttUserShoppingcart.getNumber();
        if (number == 1) {
            //购物车中对应商品的最后一件，则在表中删除
            int i = ttUserShoppingcartMapper.deleteById(ttUserShoppingcart);
            if (i <= 0) {
                throw new TaoTaoException("从购物车减少商品失败");
            }
        }else {
            //还有更多，数量减一即可
            ttUserShoppingcart.setNumber(ttUserShoppingcart.getNumber()-1);
            //修改
            int i = ttUserShoppingcartMapper.updateById(ttUserShoppingcart);
            if (i <= 0) {
                throw new TaoTaoException("减少1操作失败");
            }
        }
        //根据商品id查询商品信息返回
        RestResponse<TtGoods> response = goodsClient.getGoods(goodsId);
        TtGoods goods = response.getResult();
        ReturnShoppingCartDto returnShoppingCartDto = new ReturnShoppingCartDto();
        BeanUtils.copyProperties(goods,returnShoppingCartDto);
        returnShoppingCartDto.setNumber(ttUserShoppingcart.getNumber());
        return returnShoppingCartDto;
    }

    @Override
    public PageResult<ReturnShoppingCartDto> getShopingcartList(PageParams pageParams, String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        LambdaQueryWrapper<TtUserShoppingcart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtUserShoppingcart::getUserId,id);
        Page<TtUserShoppingcart> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<TtUserShoppingcart> ttUserAddressPage = ttUserShoppingcartMapper.selectPage(page, queryWrapper);
        List<TtUserShoppingcart> items = ttUserAddressPage.getRecords();
        long counts = ttUserAddressPage.getTotal();
        List<ReturnShoppingCartDto> items2 = new ArrayList<>();
        for (TtUserShoppingcart item : items) {
            Integer number = item.getNumber();
            String goodsId = item.getGoodsId();
            RestResponse<TtGoods> response = goodsClient.getGoods(goodsId);
            TtGoods goods = response.getResult();
            ReturnShoppingCartDto returnShoppingCartDto = new ReturnShoppingCartDto();
            BeanUtils.copyProperties(goods,returnShoppingCartDto);
            returnShoppingCartDto.setNumber(number);
            items2.add(returnShoppingCartDto);
        }
        PageResult<ReturnShoppingCartDto> ttUserAddressPageResult = new PageResult<>(items2,
                counts,pageParams.getPageNo(),pageParams.getPageSize());
        return ttUserAddressPageResult;
    }

    @Override
    @Transactional
    public boolean deleteSuccessGoods(String userId, String goodsId) {
        if (StringUtils.isEmpty(userId)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("传入的商品id为空");
        }
        LambdaQueryWrapper<TtUserShoppingcart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtUserShoppingcart::getUserId,userId).eq(TtUserShoppingcart::getGoodsId,goodsId);
        int delete = ttUserShoppingcartMapper.delete(queryWrapper);
        if (delete <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public ReturnShoppingCartDto insertShoppingcartByNum(ShoppingCartByNumDto shoppingCartByNumDto) {
        String userId = shoppingCartByNumDto.getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        String goodsId = shoppingCartByNumDto.getGoodsId();
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("传入的商品id为空");
        }
        LambdaQueryWrapper<TtUserShoppingcart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtUserShoppingcart::getUserId,userId).eq(TtUserShoppingcart::getGoodsId,goodsId);
        TtUserShoppingcart ttUserShoppingcart = ttUserShoppingcartMapper.selectOne(queryWrapper);
        if (ttUserShoppingcart == null) {
            //当前购物车没有该商品，添加，数量为1
            TtUserShoppingcart ttUserShoppingcartNew = new TtUserShoppingcart();
            ttUserShoppingcartNew.setUserId(userId);
            ttUserShoppingcartNew.setGoodsId(goodsId);
            ttUserShoppingcartNew.setNumber(shoppingCartByNumDto.getNumber());
            String id = UUID.randomUUID().toString();
            ttUserShoppingcartNew.setId(id);
            int insert = ttUserShoppingcartMapper.insert(ttUserShoppingcartNew);
            if (insert <= 0) {
                throw new TaoTaoException("添加商品到购物车失败");
            }
            //根据商品id查询商品信息返回
            RestResponse<TtGoods> response = goodsClient.getGoods(goodsId);
            TtGoods goods = response.getResult();
            ReturnShoppingCartDto returnShoppingCartDto = new ReturnShoppingCartDto();
            BeanUtils.copyProperties(goods,returnShoppingCartDto);
            returnShoppingCartDto.setNumber(ttUserShoppingcartNew.getNumber());
            return returnShoppingCartDto;
        }else {
            //不为空，当前购物车存在该商品，则在原来基础上加一即可
            ttUserShoppingcart.setNumber(ttUserShoppingcart.getNumber()+shoppingCartByNumDto.getNumber());
            //修改
            int i = ttUserShoppingcartMapper.updateById(ttUserShoppingcart);
            if (i <= 0) {
                throw new TaoTaoException("加入购物车操作失败");
            }
        }

        //根据商品id查询商品信息返回
        RestResponse<TtGoods> response = goodsClient.getGoods(goodsId);
        TtGoods goods = response.getResult();
        ReturnShoppingCartDto returnShoppingCartDto = new ReturnShoppingCartDto();
        BeanUtils.copyProperties(goods,returnShoppingCartDto);
        returnShoppingCartDto.setNumber(ttUserShoppingcart.getNumber());
        return returnShoppingCartDto;
    }

    @Override
    public void dropShoppingcart(ShoppingCartDto shoppingCartDto) {
        String userId = shoppingCartDto.getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        String goodsId = shoppingCartDto.getGoodsId();
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("传入的商品id为空");
        }
        LambdaQueryWrapper<TtUserShoppingcart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtUserShoppingcart::getUserId,userId).eq(TtUserShoppingcart::getGoodsId,goodsId);
        int delete = ttUserShoppingcartMapper.delete(queryWrapper);
        if (delete <= 0) {
            throw new TaoTaoException("从购物车中删除商品失败");
        }
    }
}
